class JavaEditor {
    constructor() {
        this.editor = null;
        this.isDebugging = false;
        this.breakpoints = new Set();
        this.currentLine = null;
        this.variables = {};
        this.debugProcess = null;
        
        this.init();
    }
    
    init() {
        this.initEditor();
        this.bindEvents();
        this.loadFromStorage();
        this.updateStatus('编辑器已就绪');
    }
    
    initEditor() {
        const textarea = document.getElementById('codeEditor');
        this.editor = CodeMirror.fromTextArea(textarea, {
            mode: 'text/x-java',
            theme: 'monokai',
            lineNumbers: true,
            autoCloseBrackets: true,
            matchBrackets: true,
            styleActiveLine: true,
            indentUnit: 4,
            indentWithTabs: false,
            lineWrapping: true,
            gutters: ['CodeMirror-linenumbers', 'breakpoints'],
            extraKeys: {
                'Ctrl-Space': 'autocomplete',
                'Cmd-Space': 'autocomplete'
            }
        });
        
        // 注册自定义hint函数
        CodeMirror.registerHelper('hint', 'java', this.javaHint.bind(this));
        
        // 设置hint选项
        this.editor.setOption('hintOptions', {
            hint: CodeMirror.hint.java,
            completeSingle: false,
            alignWithWord: true,
            closeOnUnfocus: false
        });
        
        // 监听编辑器变化
        this.editor.on('change', () => {
            this.autoSave();
        });
        
        // 监听光标位置变化
        this.editor.on('cursorActivity', () => {
            this.updateCursorInfo();
        });
        
        // 监听断点点击
        this.editor.on('gutterClick', (cm, n) => {
            this.toggleBreakpoint(n);
        });
        
        // 监听输入事件，触发自动补全
        this.editor.on('inputRead', (cm, change) => {
            if (change.text && change.text.length > 0) {
                const inputChar = change.text[0];
                // 当输入字母、点号或者删除字符时触发补全
                if (/[a-zA-Z.]/.test(inputChar) || change.text[0] === '') {
                    setTimeout(() => {
                        if (!cm.state.completionActive) {
                            cm.showHint({
                                hint: this.javaHint.bind(this),
                                completeSingle: false,
                                alignWithWord: true,
                                closeOnUnfocus: false
                            });
                        }
                    }, 150);
                }
            }
        });
    }
    
    bindEvents() {
        // 工具栏按钮
        document.getElementById('runBtn').addEventListener('click', () => this.runCode());
        document.getElementById('debugBtn').addEventListener('click', () => this.startDebug());
        document.getElementById('saveBtn').addEventListener('click', () => this.saveCode());
        document.getElementById('loadBtn').addEventListener('click', () => this.loadCode());
        document.getElementById('clearBtn').addEventListener('click', () => this.clearEditor());
        document.getElementById('clearOutputBtn').addEventListener('click', () => this.clearOutput());
        document.getElementById('testHintBtn').addEventListener('click', () => this.testHint());
        
        // 调试控制按钮
        document.getElementById('stepBtn').addEventListener('click', () => this.stepDebug());
        document.getElementById('continueBtn').addEventListener('click', () => this.continueDebug());
        document.getElementById('stopDebugBtn').addEventListener('click', () => this.stopDebug());
        
        // 主题选择
        document.getElementById('themeSelect').addEventListener('change', (e) => {
            this.changeTheme(e.target.value);
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 's':
                        e.preventDefault();
                        this.saveCode();
                        break;
                    case 'r':
                        e.preventDefault();
                        this.runCode();
                        break;
                    case 'd':
                        e.preventDefault();
                        this.startDebug();
                        break;
                }
            }
            
            if (e.key === 'F5') {
                e.preventDefault();
                this.runCode();
            }
            
            if (e.key === 'F9') {
                e.preventDefault();
                const cursor = this.editor.getCursor();
                this.toggleBreakpoint(cursor.line);
            }
        });
        
        // 模态框
        const modal = document.getElementById('modal');
        const closeBtn = document.querySelector('.close');
        closeBtn.addEventListener('click', () => {
            modal.style.display = 'none';
        });
        
        window.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.style.display = 'none';
            }
        });
    }
    
    async runCode() {
        const code = this.editor.getValue();
        if (!code.trim()) {
            this.showOutput('请输入Java代码', 'error');
            return;
        }
        
        this.updateStatus('正在编译和运行...');
        this.clearOutput();
        
        try {
            // 模拟编译和运行过程
            const result = await this.compileAndRun(code);
            this.showOutput(result.output, result.success ? 'success' : 'error');
            this.updateCompileStatus(result.success ? '编译成功' : '编译失败');
        } catch (error) {
            this.showOutput(`运行错误: ${error.message}`, 'error');
            this.updateCompileStatus('运行失败');
        }
        
        this.updateStatus('就绪');
    }
    
    async compileAndRun(code) {
        // 模拟编译和运行Java代码
        // 在实际应用中，这里应该调用后端API
        return new Promise((resolve) => {
            setTimeout(() => {
                try {
                    // 简单的代码分析和模拟执行
                    const output = this.simulateJavaExecution(code);
                    resolve({ success: true, output });
                } catch (error) {
                    resolve({ success: false, output: error.message });
                }
            }, 1000);
        });
    }
    
    simulateJavaExecution(code) {
        let output = '';
        
        // 查找System.out.println语句
        const printRegex = /System\.out\.println\s*\(\s*([^)]+)\s*\)/g;
        let match;
        
        while ((match = printRegex.exec(code)) !== null) {
            let content = match[1].trim();
            
            // 处理字符串字面量
            if (content.startsWith('"') && content.endsWith('"')) {
                content = content.slice(1, -1);
            } else if (content.includes('+')) {
                // 简单的字符串连接处理
                content = this.evaluateSimpleExpression(content, code);
            }
            
            output += content + '\n';
        }
        
        // 查找循环语句
        const forRegex = /for\s*\(\s*int\s+(\w+)\s*=\s*(\d+);\s*\1\s*<=\s*(\d+);\s*\1\+\+\s*\)/g;
        let forMatch;
        
        while ((forMatch = forRegex.exec(code)) !== null) {
            const varName = forMatch[1];
            const start = parseInt(forMatch[2]);
            const end = parseInt(forMatch[3]);
            
            // 查找循环体中的输出语句
            const loopStart = code.indexOf('{', forMatch.index);
            const loopEnd = this.findMatchingBrace(code, loopStart);
            const loopBody = code.substring(loopStart + 1, loopEnd);
            
            for (let i = start; i <= end; i++) {
                const loopOutput = loopBody.replace(new RegExp(varName, 'g'), i.toString());
                const loopPrintRegex = /System\.out\.println\s*\(\s*([^)]+)\s*\)/g;
                let loopPrintMatch;
                
                while ((loopPrintMatch = loopPrintRegex.exec(loopOutput)) !== null) {
                    let loopContent = loopPrintMatch[1].trim();
                    if (loopContent.startsWith('"') && loopContent.endsWith('"')) {
                        loopContent = loopContent.slice(1, -1);
                    }
                    loopContent = loopContent.replace(/\+\s*\w+/g, (match) => {
                        const varRef = match.replace('+', '').trim();
                        return varRef === varName ? i.toString() : match;
                    });
                    output += loopContent + '\n';
                }
            }
        }
        
        return output || '程序执行完成，无输出。';
    }
    
    evaluateSimpleExpression(expr, code) {
        // 简单的表达式求值
        try {
            // 查找变量定义
            const varRegex = /int\s+(\w+)\s*=\s*(\d+)/g;
            const variables = {};
            let varMatch;
            
            while ((varMatch = varRegex.exec(code)) !== null) {
                variables[varMatch[1]] = parseInt(varMatch[2]);
            }
            
            // 替换变量
            let result = expr;
            for (const [varName, value] of Object.entries(variables)) {
                result = result.replace(new RegExp('\\b' + varName + '\\b', 'g'), value.toString());
            }
            
            // 移除引号并计算
            result = result.replace(/"/g, '');
            result = result.replace(/\s*\+\s*/g, '');
            
            return result;
        } catch (error) {
            return expr;
        }
    }
    
    findMatchingBrace(code, start) {
        let count = 1;
        for (let i = start + 1; i < code.length; i++) {
            if (code[i] === '{') count++;
            if (code[i] === '}') count--;
            if (count === 0) return i;
        }
        return code.length;
    }
    
    startDebug() {
        if (this.isDebugging) {
            this.showMessage('调试器已在运行中');
            return;
        }
        
        const code = this.editor.getValue();
        if (!code.trim()) {
            this.showOutput('请输入Java代码', 'error');
            return;
        }
        
        this.isDebugging = true;
        this.updateDebugControls(true);
        this.updateStatus('调试模式已启动');
        this.showOutput('调试器已启动，点击单步执行开始调试', 'info');
        
        // 模拟调试过程
        this.simulateDebugSession(code);
    }
    
    simulateDebugSession(code) {
        // 解析代码行
        const lines = code.split('\n');
        let currentLineIndex = 0;
        
        // 查找main方法开始行
        for (let i = 0; i < lines.length; i++) {
            if (lines[i].includes('public static void main')) {
                currentLineIndex = i + 1; // 跳过方法声明行
                break;
            }
        }
        
        this.currentLine = currentLineIndex;
        this.highlightCurrentLine(currentLineIndex);
        this.updateVariables({ 'args': 'String[]' });
    }
    
    stepDebug() {
        if (!this.isDebugging) return;
        
        const code = this.editor.getValue();
        const lines = code.split('\n');
        
        if (this.currentLine < lines.length) {
            const currentCodeLine = lines[this.currentLine].trim();
            
            // 模拟执行当前行
            this.executeDebugLine(currentCodeLine);
            
            this.currentLine++;
            
            // 跳过空行和注释
            while (this.currentLine < lines.length && 
                   (lines[this.currentLine].trim() === '' || 
                    lines[this.currentLine].trim().startsWith('//'))) {
                this.currentLine++;
            }
            
            if (this.currentLine < lines.length) {
                this.highlightCurrentLine(this.currentLine);
            } else {
                this.stopDebug();
                this.showOutput('程序执行完成', 'success');
            }
        }
    }
    
    executeDebugLine(line) {
        // 模拟执行代码行并更新变量
        if (line.includes('int ') && line.includes('=')) {
            const match = line.match(/int\s+(\w+)\s*=\s*(\d+|\w+(?:\s*[+\-*/]\s*\w+)*)/);            if (match) {
                const varName = match[1];
                const expression = match[2];
                let value;
                
                try {
                    // 简单的表达式计算
                    if (/^\d+$/.test(expression)) {
                        value = parseInt(expression);
                    } else {
                        // 处理简单的算术表达式
                        value = this.evaluateArithmetic(expression);
                    }
                    
                    this.variables[varName] = value;
                    this.updateVariables(this.variables);
                } catch (error) {
                    this.variables[varName] = expression;
                    this.updateVariables(this.variables);
                }
            }
        } else if (line.includes('System.out.println')) {
            const match = line.match(/System\.out\.println\s*\(\s*([^)]+)\s*\)/);
            if (match) {
                let output = match[1].trim();
                if (output.startsWith('"') && output.endsWith('"')) {
                    output = output.slice(1, -1);
                } else {
                    // 替换变量
                    for (const [varName, value] of Object.entries(this.variables)) {
                        output = output.replace(new RegExp('\\b' + varName + '\\b', 'g'), value.toString());
                    }
                    output = output.replace(/"/g, '').replace(/\s*\+\s*/g, '');
                }
                this.showOutput(output, 'info');
            }
        }
    }
    
    evaluateArithmetic(expression) {
        // 替换变量
        let expr = expression;
        for (const [varName, value] of Object.entries(this.variables)) {
            expr = expr.replace(new RegExp('\\b' + varName + '\\b', 'g'), value.toString());
        }
        
        // 简单的算术计算
        try {
            return Function('"use strict"; return (' + expr + ')')();
        } catch (error) {
            return expression;
        }
    }
    
    continueDebug() {
        if (!this.isDebugging) return;
        
        // 继续执行到下一个断点或程序结束
        const code = this.editor.getValue();
        const lines = code.split('\n');
        
        while (this.currentLine < lines.length) {
            if (this.breakpoints.has(this.currentLine)) {
                this.highlightCurrentLine(this.currentLine);
                this.showOutput(`在第 ${this.currentLine + 1} 行遇到断点`, 'warning');
                return;
            }
            
            const currentCodeLine = lines[this.currentLine].trim();
            this.executeDebugLine(currentCodeLine);
            this.currentLine++;
            
            // 跳过空行和注释
            while (this.currentLine < lines.length && 
                   (lines[this.currentLine].trim() === '' || 
                    lines[this.currentLine].trim().startsWith('//'))) {
                this.currentLine++;
            }
        }
        
        this.stopDebug();
        this.showOutput('程序执行完成', 'success');
    }
    
    stopDebug() {
        this.isDebugging = false;
        this.currentLine = null;
        this.variables = {};
        this.updateDebugControls(false);
        this.clearHighlight();
        this.updateVariables({});
        this.updateStatus('调试已停止');
    }
    
    toggleBreakpoint(line) {
        if (this.breakpoints.has(line)) {
            this.breakpoints.delete(line);
            this.editor.setGutterMarker(line, 'breakpoints', null);
        } else {
            this.breakpoints.add(line);
            const marker = document.createElement('div');
            marker.className = 'breakpoint';
            this.editor.setGutterMarker(line, 'breakpoints', marker);
        }
        
        this.updateBreakpointsList();
    }
    
    highlightCurrentLine(line) {
        this.clearHighlight();
        this.editor.addLineClass(line, 'background', 'current-line');
        this.editor.setCursor(line, 0);
    }
    
    clearHighlight() {
        for (let i = 0; i < this.editor.lineCount(); i++) {
            this.editor.removeLineClass(i, 'background', 'current-line');
        }
    }
    
    updateDebugControls(debugging) {
        document.getElementById('stepBtn').disabled = !debugging;
        document.getElementById('continueBtn').disabled = !debugging;
        document.getElementById('stopDebugBtn').disabled = !debugging;
        document.getElementById('debugBtn').disabled = debugging;
    }
    
    updateVariables(vars) {
        const container = document.getElementById('variables');
        container.innerHTML = '';
        
        for (const [name, value] of Object.entries(vars)) {
            const item = document.createElement('div');
            item.className = 'variable-item';
            item.innerHTML = `
                <span class="variable-name">${name}</span>
                <span class="variable-value">${value}</span>
                <span class="variable-type">${typeof value}</span>
            `;
            container.appendChild(item);
        }
    }
    
    updateBreakpointsList() {
        const container = document.getElementById('breakpoints');
        container.innerHTML = '';
        
        for (const line of this.breakpoints) {
            const item = document.createElement('div');
            item.className = 'breakpoint-item';
            item.textContent = `第 ${line + 1} 行`;
            item.addEventListener('click', () => {
                this.editor.setCursor(line, 0);
                this.editor.focus();
            });
            container.appendChild(item);
        }
    }
    
    saveCode() {
        const code = this.editor.getValue();
        const fileName = document.getElementById('fileName').textContent;
        
        // 保存到本地存储
        localStorage.setItem('javaEditor_code', code);
        localStorage.setItem('javaEditor_fileName', fileName);
        
        // 创建下载链接
        const blob = new Blob([code], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.click();
        URL.revokeObjectURL(url);
        
        this.updateStatus('代码已保存');
        this.showMessage('代码已保存到本地');
    }
    
    loadCode() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.java,.txt';
        input.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.editor.setValue(e.target.result);
                    document.getElementById('fileName').textContent = file.name;
                    this.updateStatus('代码已加载');
                };
                reader.readAsText(file);
            }
        });
        input.click();
    }
    
    clearEditor() {
        if (confirm('确定要清空编辑器内容吗？')) {
            this.editor.setValue('');
            this.clearOutput();
            this.updateStatus('编辑器已清空');
        }
    }
    
    clearOutput() {
        document.getElementById('output').innerHTML = '';
    }
    
    showOutput(text, type = 'info') {
        const output = document.getElementById('output');
        const div = document.createElement('div');
        div.className = `output-${type}`;
        div.textContent = text;
        output.appendChild(div);
        output.scrollTop = output.scrollHeight;
    }
    
    changeTheme(theme) {
        this.editor.setOption('theme', theme);
        localStorage.setItem('javaEditor_theme', theme);
    }
    
    updateStatus(text) {
        document.getElementById('status').textContent = text;
    }
    
    updateCompileStatus(text) {
        document.getElementById('compileStatus').textContent = text;
    }
    
    updateCursorInfo() {
        const cursor = this.editor.getCursor();
        document.getElementById('lineInfo').textContent = `行: ${cursor.line + 1}, 列: ${cursor.ch + 1}`;
    }
    
    autoSave() {
        clearTimeout(this.autoSaveTimer);
        this.autoSaveTimer = setTimeout(() => {
            localStorage.setItem('javaEditor_autoSave', this.editor.getValue());
        }, 2000);
    }
    
    loadFromStorage() {
        const savedCode = localStorage.getItem('javaEditor_code');
        const savedTheme = localStorage.getItem('javaEditor_theme');
        const autoSavedCode = localStorage.getItem('javaEditor_autoSave');
        
        if (autoSavedCode && autoSavedCode !== savedCode) {
            if (confirm('检测到自动保存的内容，是否恢复？')) {
                this.editor.setValue(autoSavedCode);
            }
        } else if (savedCode) {
            this.editor.setValue(savedCode);
        }
        
        if (savedTheme) {
            document.getElementById('themeSelect').value = savedTheme;
            this.changeTheme(savedTheme);
        }
    }
    
    showMessage(message, title = '提示') {
        const modal = document.getElementById('modal');
        document.getElementById('modalTitle').textContent = title;
        document.getElementById('modalBody').textContent = message;
        modal.style.display = 'block';
        
        document.getElementById('modalOk').onclick = () => {
            modal.style.display = 'none';
        };
        
        document.getElementById('modalCancel').style.display = 'none';
    }
    
    // 测试代码补全功能
    testHint() {
        this.showOutput('测试代码补全功能...', 'info');
        this.showOutput('1. 输入字母时应自动显示补全提示', 'info');
        this.showOutput('2. 按 Ctrl/Cmd + Space 手动触发补全', 'info');
        this.showOutput('3. 尝试输入: cla, Sys, for, main, sout', 'info');
        
        // 手动触发补全测试
        setTimeout(() => {
            this.editor.showHint({
                hint: this.javaHint.bind(this),
                completeSingle: false
            });
        }, 500);
    }
    
    // Java代码补全功能
    javaHint(cm, options) {
        const cursor = cm.getCursor();
        const line = cm.getLine(cursor.line);
        const start = cursor.ch;
        let end = cursor.ch;
        
        // 找到当前单词的开始位置
        let wordStart = start;
        while (wordStart > 0 && /[a-zA-Z0-9_$]/.test(line.charAt(wordStart - 1))) {
            wordStart--;
        }
        
        const currentWord = line.slice(wordStart, end).toLowerCase();
        
        // Java关键字
        const javaKeywords = [
            'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char',
            'class', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum',
            'extends', 'final', 'finally', 'float', 'for', 'goto', 'if', 'implements',
            'import', 'instanceof', 'int', 'interface', 'long', 'native', 'new', 'package',
            'private', 'protected', 'public', 'return', 'short', 'static', 'strictfp',
            'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient',
            'try', 'void', 'volatile', 'while'
        ];
        
        // 常用Java类和方法
        const javaClasses = [
            'String', 'Integer', 'Double', 'Float', 'Boolean', 'Character', 'Byte',
            'Short', 'Long', 'Object', 'Class', 'System', 'Math', 'Random',
            'ArrayList', 'HashMap', 'HashSet', 'LinkedList', 'Vector', 'Stack',
            'Scanner', 'BufferedReader', 'FileReader', 'PrintWriter', 'File',
            'Exception', 'RuntimeException', 'IOException', 'NullPointerException'
        ];
        
        // 常用方法
        const javaMethods = [
            'println', 'print', 'length', 'charAt', 'substring', 'indexOf', 'toLowerCase',
            'toUpperCase', 'trim', 'replace', 'split', 'equals', 'compareTo',
            'add', 'remove', 'get', 'set', 'size', 'isEmpty', 'contains',
            'hasNext', 'next', 'close', 'read', 'write', 'flush',
            'toString', 'valueOf', 'parseInt', 'parseDouble', 'parseFloat'
        ];
        
        // 代码模板
        const javaTemplates = [
            {
                text: 'main',
                displayText: 'main - main method',
                template: 'public static void main(String[] args) {\n    \n}'
            },
            {
                text: 'sout',
                displayText: 'sout - System.out.println',
                template: 'System.out.println();'
            },
            {
                text: 'for',
                displayText: 'for - for loop',
                template: 'for (int i = 0; i < length; i++) {\n    \n}'
            },
            {
                text: 'while',
                displayText: 'while - while loop',
                template: 'while (condition) {\n    \n}'
            },
            {
                text: 'if',
                displayText: 'if - if statement',
                template: 'if (condition) {\n    \n}'
            },
            {
                text: 'try',
                displayText: 'try - try-catch block',
                template: 'try {\n    \n} catch (Exception e) {\n    e.printStackTrace();\n}'
            }
        ];
        
        let suggestions = [];
        
        // 检查是否在输入方法调用
        const beforeCursor = line.slice(0, cursor.ch);
        const dotIndex = beforeCursor.lastIndexOf('.');
        
        if (dotIndex !== -1 && dotIndex < cursor.ch - 1) {
            // 方法补全
            const objectPart = beforeCursor.slice(0, dotIndex).trim();
            const methodPart = beforeCursor.slice(dotIndex + 1).toLowerCase();
            
            // 根据对象类型提供相应的方法
            if (objectPart.includes('System.out')) {
                suggestions = ['println', 'print', 'printf'].filter(method => 
                    method.toLowerCase().startsWith(methodPart)
                ).map(method => ({
                    text: method + '()',
                    displayText: method + '() - System.out method'
                }));
            } else if (objectPart.match(/".*"|\w+\s*\(.*\)\.\w*|\w+/)) {
                // String方法
                const stringMethods = [
                    'length', 'charAt', 'substring', 'indexOf', 'toLowerCase',
                    'toUpperCase', 'trim', 'replace', 'split', 'equals', 'compareTo'
                ];
                suggestions = stringMethods.filter(method => 
                    method.toLowerCase().startsWith(methodPart)
                ).map(method => ({
                    text: method + '()',
                    displayText: method + '() - String method'
                }));
            } else {
                // 通用方法
                suggestions = javaMethods.filter(method => 
                    method.toLowerCase().startsWith(methodPart)
                ).map(method => ({
                    text: method,
                    displayText: method + ' - method'
                }));
            }
        } else {
            // 关键字补全
            suggestions = suggestions.concat(
                javaKeywords.filter(keyword => 
                    keyword.startsWith(currentWord)
                ).map(keyword => ({
                    text: keyword,
                    displayText: keyword + ' - keyword',
                    className: 'cm-keyword'
                }))
            );
            
            // 类名补全
            suggestions = suggestions.concat(
                javaClasses.filter(className => 
                    className.toLowerCase().startsWith(currentWord)
                ).map(className => ({
                    text: className,
                    displayText: className + ' - class',
                    className: 'cm-type'
                }))
            );
            
            // 模板补全
            suggestions = suggestions.concat(
                javaTemplates.filter(template => 
                    template.text.startsWith(currentWord)
                ).map(template => ({
                    text: template.template,
                    displayText: template.displayText,
                    className: 'cm-template'
                }))
            );
            
            // 从当前代码中提取变量和方法名
            const codeVariables = this.extractVariablesFromCode(cm.getValue());
            suggestions = suggestions.concat(
                codeVariables.filter(variable => 
                    variable.toLowerCase().startsWith(currentWord) && 
                    variable.toLowerCase() !== currentWord
                ).map(variable => ({
                    text: variable,
                    displayText: variable + ' - variable',
                    className: 'cm-variable'
                }))
            );
        }
        
        // 去重并排序
        suggestions = suggestions.filter((item, index, self) => 
            index === self.findIndex(t => t.text === item.text)
        ).sort((a, b) => a.text.localeCompare(b.text));
        
        return {
            list: suggestions,
            from: { line: cursor.line, ch: wordStart },
            to: { line: cursor.line, ch: end }
        };
    }
    
    // 从代码中提取变量名
    extractVariablesFromCode(code) {
        const variables = new Set();
        
        // 匹配变量声明
        const varRegex = /(?:int|String|double|float|boolean|char|byte|short|long)\s+(\w+)/g;
        let match;
        while ((match = varRegex.exec(code)) !== null) {
            variables.add(match[1]);
        }
        
        // 匹配方法名
        const methodRegex = /(?:public|private|protected)?\s*(?:static)?\s*(?:\w+)\s+(\w+)\s*\(/g;
        while ((match = methodRegex.exec(code)) !== null) {
            if (match[1] !== 'main' && match[1] !== 'class') {
                variables.add(match[1]);
            }
        }
        
        return Array.from(variables);
    }
}

// 初始化编辑器
document.addEventListener('DOMContentLoaded', () => {
    new JavaEditor();
});